package com.itrip.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itrip.auth.config.JwtUtil;
import com.itrip.auth.entity.User;
import com.itrip.auth.service.impl.MailServiceImpl;
import com.itrip.auth.service.UserService;
import com.itrip.auth.service.impl.UserServiceImpl;
import com.itrip.beans.vo.ItripTokenVO;
import com.itrip.utils.vo.DtoUtil;
import com.itrip.utils.dto.Dto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Lenovo
 * @description: 用户登录
 * @date: 2020/2/28 15:06
 */
@CrossOrigin("*")
@RestController
@RequestMapping("/auth/api")
public class LoginUserController {
    @Resource
    private UserService userService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @PostMapping("/dologin")
    public Dto login(@RequestParam String name,
                     @RequestParam String password,
                     HttpServletRequest request) {
        User itripUser = new User();
        itripUser.setUserCode(name);
        itripUser.setUserPassword(password);
        if (((!"".equals(name)) || (null != name)) && ((!"".equals(password)) || (null != password))) {
            User user = null;
            try {
                user = userService.login(itripUser);
            } catch (Exception e) {
                return DtoUtil.returnFail("服务器异常");
            }
            if (user != null) {
                if (user.getActivated() == 1) {//判断用户是否激活
                    // 生成token
                    String token = JwtUtil.getToken(user.getUserName());
                    //返回ItripTokenVO
                    ItripTokenVO tokenVO = new ItripTokenVO(token,
                            Calendar.getInstance().getTimeInMillis() + 2 * 60 * 60 * 1000,//2h有效期
                            Calendar.getInstance().getTimeInMillis());
                    //上传当前用户
                    stringRedisTemplate.opsForValue().set(token, user.getId().toString());
                    return DtoUtil.returnDataSuccess(tokenVO);

                } else {//未激活返回：用户未激活
                    return DtoUtil.returnFail("用户未激活");
                }
            } else {//不正确返回：账号密码输入错误
                return DtoUtil.returnFail("账号密码输入错误！");
            }
        } else {
            return DtoUtil.returnFail("参数错误！检查提交的参数名称是否正确");
        }
    }

    //登出
    @GetMapping("/logout")
    public Dto logOut(HttpServletRequest request) {
        String token = request.getHeader("token");
        //删除rdeis
        stringRedisTemplate.delete(token);
        return DtoUtil.returnSuccess("注销成功");
    }

    @GetMapping("/ckusr")
    public Dto register(@RequestParam String name) {
        User user = new User();
        user.setUserCode(name);
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        wrapper.eq("user_code", name);
        User user1 = userService.getOne(wrapper);
        if (user1 != null) {
            return DtoUtil.returnFail("用户已存在");
        }

        return DtoUtil.returnSuccess("可用");
    }


    @Autowired
    private MailServiceImpl mailService;

    @RequestMapping("/doregister")
    public String getCheckCode(@RequestBody User user) {
        user.setUserPassword(UserServiceImpl.string2MD5(user.getUserPassword()));
        userService.save(user);
        String checkCode = String.valueOf(new Random().nextInt(899999) + 100000);
        stringRedisTemplate.opsForValue().set(user.getUserCode(), checkCode);
        String message = "您的注册验证码为：" + checkCode;
        try {
            System.out.println(user.getUserCode());
            mailService.sendSimpleMail(user.getUserCode(), "注册验证码", message);
        } catch (Exception e) {
            return e.getMessage();
        }
        return checkCode;
    }

    @PutMapping("/activate")
    public Dto act(@RequestParam String user, @RequestParam String code) {

        if (stringRedisTemplate.opsForValue().get(user).equals(code)) {
            QueryWrapper<User> wrapper = new QueryWrapper<User>();
            wrapper.eq("user_code", user);
            User actUser = userService.getOne(wrapper);
            actUser.setActivated(1);
            userService.saveOrUpdate(actUser);
            stringRedisTemplate.delete(user);
            return DtoUtil.returnSuccess("激活成功");
        } else {
            return DtoUtil.returnFail("激活失败");
        }
    }
}
